package cn.fl.mcr.controller;

import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.service.IMcrCstBlackListService;
import cn.fl.mcr.vo.McrCstBlackListVO;
import cn.fl.spl.utils.FileUtil;
import cn.fl.system.constant.SysLogConstant;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.McrCstBlackListQC;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Description: 客户小贷黑名单 控制层
 */
@Controller
@RequestMapping("/mcr/mcrCstBlackList")
public class McrCstBlackListController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(McrCstBlackListController.class);

	/**
	 * McrCstBlackList 服务层BEAN
	 */
	@Autowired
	private IMcrCstBlackListService mcrCstBlackListService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toListPage", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		ModelAndView view = new ModelAndView("mcr/mcrCstBlackList/mcrCstBlackListList");
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toListPage", "加载列表页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载新增.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		ModelAndView view = new ModelAndView("mcr/mcrCstBlackList/mcrCstBlackListAdd");
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载新增.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载修改页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("mcr/mcrCstBlackList/mcrCstBlackListAdd");
		view.addObject("id", id);
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载修改.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toDetailPage", "加载例子详细页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("mcr/mcrCstBlackList/mcrCstBlackListDetail");
		view.addObject("id", id);
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toDetailPage", " 加载例子详细页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到导入黑名单页面
	 */
	@RequestMapping(value = "/toImportBlackListPage.do", method = {RequestMethod.GET})
	public ModelAndView toMcrCustomerPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toImportBlackListPage", "加载导入黑名单页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

		ModelAndView view = new ModelAndView("mcr/mcrCstBlackList/mcrImportBlackListPage");

		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toImportBlackListPage", "加载导入黑名单页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}


	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do")
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response, McrCstBlackListQC qc) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initList", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
        String forbiddenTmStr = request.getParameter("forbiddenTmStr");
        if(!StringUtils.isEmpty(forbiddenTmStr)){
            qc.setForbiddenTm(DateUtils.formatStringToDate(forbiddenTmStr, "yyyy-MM-dd"));
        }
		page.setCondition(qc);

		Pager pager = mcrCstBlackListService.searchListPage(page);
		List<McrCstBlackListVO> list = (List<McrCstBlackListVO>) pager.getResultList();
		ListPageVO<McrCstBlackListVO> listPage = new ListPageVO<McrCstBlackListVO>(list, pager.getTotalCount());
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initList", "加载列表页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	
	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response, McrCstBlackListVO entity) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		if(entity == null){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("新增失败，参数不能为空");
			return result;
		}
		try {
			Long id = this.mcrCstBlackListService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response, McrCstBlackListVO entity) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(entity == null){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("新增失败，参数不能为空");
			return result;
		}
		try {
			boolean success = this.mcrCstBlackListService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(),ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.error(logger, "modify", "修改成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(),ex);
		}
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "modify", "修改成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());

		return result;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.mcrCstBlackListService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "remove", "移除对象失败,主键["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.error(logger, "remove", "移除对象失败,主键["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		}
		
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			McrCstBlackListVO vo = this.mcrCstBlackListService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在!");
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "根据主键获取对象失败,主键["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.error(logger, "getById", "根据主键获取对象失败,主键["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		}

		return result;
	}

    /**
     * 作废记录
     */
    @RequestMapping(value = "/cancel.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object cancel(HttpServletRequest request, HttpServletResponse response, McrCstBlackListVO entity) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        try {
            if(entity == null || entity.getId() == null){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("作废失败，ID不能为空");
                return result;
            }
            McrCstBlackListVO modifyVo = new McrCstBlackListVO();
            modifyVo.setId(entity.getId());
            //是否有效改为无效
            modifyVo.setIsValid(0);
            boolean success = this.mcrCstBlackListService.modify(modifyVo);
            if(!success){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
                BaseLogUtils.info(logger, "modify", "作废失败.[ID="+entity.getId()+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "modify", "作废成功.[ID="+entity.getId()+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "modify", "作废失败.[ID="+entity.getId()+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "modify", "作废失败.[ID="+entity.getId()+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

	/**
	 * 下载模板
	 */
	@RequestMapping(value = "/download.do", method = {RequestMethod.POST})
	@ResponseBody
	public DataResultVO download(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "download", "下载模板" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		DataResultVO vo =new DataResultVO(BaseConstant.IS_YESNO_YES,"模板获取成功");
		String tempPath= FileUtil.getSavePath("template/mcr/mcrBlackListTemplate.xlsx");
		tempPath = tempPath.replace(
				PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH),
				PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH));
		Long endTm = System.currentTimeMillis();
		vo.setData(tempPath);
		BaseLogUtils.info(logger, "download", " 下载模板.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
		BaseLogUtils.info(logger, "download", " 下载模板.返回结果：" + tempPath, CurrentThreadContext.getCurrentUserName());
		return vo;
	}

	/**
	 * 导入黑名单列表
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/importData.do", method = {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public DataResultVO importData(HttpServletRequest request, HttpServletResponse response) throws IOException {
		final String methodName = "importData";
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, methodName, "excel导入.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "excel导入成功");
		String filePath = request.getParameter("filePath");//文件路径
		try {
			String rootPath = PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH);
			String realPath = rootPath + filePath;
			String errorMsg = this.mcrCstBlackListService.importData(realPath);
			if(StringUtils.isNotBlank(errorMsg)){
				result.setInfo(errorMsg);
			}

			BaseLogUtils.info(logger, methodName, "上传文件路径：" + realPath);
		} catch (BaseException ex) {
			BaseLogUtils.error(logger, methodName, "excel导入失败", CurrentThreadContext.getCurrentUserName(), ex);
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		} catch (Exception e) {
			BaseLogUtils.error(logger, methodName, "excel导入失败.", CurrentThreadContext.getCurrentUserName(), e);
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("excel导入失败");
		}
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, methodName, "excel导入.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
		BaseLogUtils.info(logger, methodName, "excel导入.返回结果：" + JSONObject.toJSONString(result), CurrentThreadContext.getCurrentUserName());
		return result;
	}
}

